package jxc.servlet.user;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import eu.log.LogFactory;
import eu.log.Logger;
import eu.web.security.access.AccessIdentity;
import eu.web.security.access.IdentityFetcher;
import jxc.base.helper.Encrypt;
import jxc.data.hibernate.dao.OperatorDAO;
import jxc.data.hibernate.pojo.Operator;

/**
 * 登录servlet
 */
@WebServlet(urlPatterns="/login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
    Logger logger=LogFactory.getLogger("登录");
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
    }

    /**
     * 登出
     */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		AccessIdentity aid=IdentityFetcher.fetch(request);
		aid.clear();
		response.sendRedirect("login.jsp");
	}


	/**
	 * 登录
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		OperatorDAO ud=new OperatorDAO();
		String username=request.getParameter("username");
		String password=Encrypt.md5(request.getParameter("password"));
		Operator user=ud.getByUsername(username);
		if(user==null||!user.getPassword().equals(password)){
			request.setAttribute("message", "登录失败");
			logger.notice("登录失败:username="+username+" password="+request.getParameter("password"));
			request.getRequestDispatcher("login.jsp").forward(request,response);
			return;
		}
		logger.info("登录成功:username="+username);
		AccessIdentity aid=IdentityFetcher.fetch(request);
		if("normal".equals(user.getPower())){
			aid.addPower("normal");
			request.getSession().setAttribute("power", "normal");
		}else if("admin".equals(user.getPower())){
			aid.addPower("normal");
			aid.addPower("admin");
			request.getSession().setAttribute("power", "admin");
		}
		aid.setUser(user);
		response.sendRedirect("desktop.jsp");
	}

}
